package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.server.KtorServer
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.viewmodel.NetworkViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class NetworkConfigFragment : BaseFragment() {
    
    private val viewModel: NetworkViewModel by viewModels()
    
    // UI组件
    private lateinit var serverStatusText: TextView
    private lateinit var startServerButton: Button
    private lateinit var stopServerButton: Button
    private lateinit var portEditText: EditText
    private lateinit var hostEditText: EditText
    private lateinit var applyConfigButton: Button
    private lateinit var saveExternalApiButton: Button
    private lateinit var networkStatusText: TextView
    private lateinit var checkNetworkButton: Button
    private lateinit var serverInfoText: TextView
    private lateinit var externalApiUrlEditText: EditText
    private lateinit var tokenEditText: EditText
    private lateinit var externalApiEnabledSwitch: SwitchCompat
    
    private var isInitializing = true
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_network_config, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化UI组件
        initViews(view)
        
        // 设置点击事件
        setupClickListeners()
        
        // 观察LiveData
        observeViewModel()
        
        // 初始化UI状态
        initializeUI()
    }
    
    private fun initViews(view: View) {
        serverStatusText = view.findViewById(R.id.serverStatusText)
        startServerButton = view.findViewById(R.id.startServerButton)
        stopServerButton = view.findViewById(R.id.stopServerButton)
        portEditText = view.findViewById(R.id.portEditText)
        hostEditText = view.findViewById(R.id.hostEditText)
        applyConfigButton = view.findViewById(R.id.applyConfigButton)
        networkStatusText = view.findViewById(R.id.networkStatusText)
        checkNetworkButton = view.findViewById(R.id.checkNetworkButton)
        serverInfoText = view.findViewById(R.id.serverInfoText)
        externalApiUrlEditText = view.findViewById(R.id.externalApiUrlEditText)
        tokenEditText = view.findViewById(R.id.tokenEditText)
        saveExternalApiButton = view.findViewById(R.id.saveExternalApiButton)
        externalApiEnabledSwitch = view.findViewById(R.id.externalApiEnabledSwitch)
    }
    
    private fun setupClickListeners() {
        // 启动服务器按钮 - 自动检查服务器状态
        startServerButton.setOnClickListener {
            val port = getPortFromInput()
            val host = getHostFromInput()
            viewModel.startServer(port, host)
            
            // 记录启动服务器日志
            requireContext().logConfigChange(
                scope = viewLifecycleOwner.lifecycleScope,
                subType = "SERVER_CONTROL",
                description = "启动服务器",
                oldValue = "未运行",
                newValue = "启动中 - http://$host:$port"
            )
        }
        
        // 停止服务器按钮
        stopServerButton.setOnClickListener {
            val port = viewModel.currentPort.value ?: KtorServer.DEFAULT_PORT
            val host = viewModel.currentHost.value ?: KtorServer.DEFAULT_HOST
            
            viewModel.stopServer()
            
            // 记录停止服务器日志
            requireContext().logConfigChange(
                scope = viewLifecycleOwner.lifecycleScope,
                subType = "SERVER_CONTROL",
                description = "停止服务器",
                oldValue = "运行中 - http://$host:$port",
                newValue = "已停止"
            )
        }
        
        // 应用配置按钮 - 自动重启服务器
        applyConfigButton.setOnClickListener {
            val port = getPortFromInput()
            val host = getHostFromInput()
            
            if (port in 1..65535) {
                val oldPort = viewModel.currentPort.value ?: KtorServer.DEFAULT_PORT
                val oldHost = viewModel.currentHost.value ?: KtorServer.DEFAULT_HOST
                
                viewModel.applyNetworkConfig(port, host)
                Toast.makeText(context, "配置已应用，服务器正在重启...", Toast.LENGTH_SHORT).show()
                
                // 记录应用配置日志
                val changes = mutableListOf<String>()
                if (oldPort != port) changes.add("端口: $oldPort → $port")
                if (oldHost != host) changes.add("主机: $oldHost → $host")
                
                if (changes.isNotEmpty()) {
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "SERVER_CONFIG",
                        description = "应用服务器配置并重启: ${changes.joinToString(", ")}",
                        oldValue = "http://$oldHost:$oldPort",
                        newValue = "http://$host:$port"
                    )
                }
            } else {
                Toast.makeText(context, "端口号必须在1-65535之间", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 检查网络状态按钮
        checkNetworkButton.setOnClickListener {
            viewModel.checkNetworkStatus()
            
            // 记录检查网络状态日志
            requireContext().logConfigChange(
                scope = viewLifecycleOwner.lifecycleScope,
                subType = "NETWORK_CHECK",
                description = "检查网络状态",
                oldValue = "",
                newValue = "执行网络状态检查"
            )
        }

        // 保存外部接口配置
        saveExternalApiButton.setOnClickListener {
            val url = externalApiUrlEditText.text.toString().trim()
            val token = tokenEditText.text.toString().trim()
            val enabled = externalApiEnabledSwitch.isChecked
            
            if (url.isEmpty()) {
                Toast.makeText(context, "请输入外部接口地址", Toast.LENGTH_SHORT).show()
            } else {
                viewLifecycleOwner.lifecycleScope.launch {
                    // 获取旧值
                    val oldUrl = viewModel.externalApiUrl.value ?: ""
                    val oldToken = viewModel.token.value ?: ""
                    val oldEnabled = viewModel.externalApiEnabled.value ?: false
                    
                    // 保存新值
                    viewModel.saveExternalApiUrl(url)
                    viewModel.saveToken(token)
                    viewModel.saveExternalApiEnabled(enabled)
                    
                    // 构建变更详情
                    val changes = mutableListOf<String>()
                    if (oldUrl != url) changes.add("接口地址: $oldUrl → $url")
                    if (oldToken != token) {
                        val oldTokenMask = if (oldToken.isNotEmpty()) "****" else "(空)"
                        val newTokenMask = if (token.isNotEmpty()) "****" else "(空)"
                        changes.add("Token: $oldTokenMask → $newTokenMask")
                    }
                    if (oldEnabled != enabled) {
                        changes.add("启用状态: ${if (oldEnabled) "启用" else "禁用"} → ${if (enabled) "启用" else "禁用"}")
                    }
                    
                    // 记录日志
                    if (changes.isNotEmpty()) {
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "EXTERNAL_API_CONFIG",
                            description = "修改外部接口配置: ${changes.joinToString(", ")}",
                            oldValue = "URL: $oldUrl, Enabled: $oldEnabled",
                            newValue = changes.joinToString("\n")
                        )
                    }
                    
                    withContext(Dispatchers.Main) {
                        Toast.makeText(context, "外部接口配置已保存", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
        
        // 外部接口启用/禁用开关监听
        externalApiEnabledSwitch.setOnCheckedChangeListener { _, isChecked ->
            // 只在非初始化状态时显示提示和记录日志，避免加载配置时触发
            if (!isInitializing) {
                if (isChecked) {
                    // 尝试启用时，检查外部接口地址是否存在
                    val currentUrl = viewModel.externalApiUrl.value?.trim() ?: ""
                    
                    if (currentUrl.isEmpty()) {
                        // 地址为空，不允许启用
                        externalApiEnabledSwitch.isChecked = false
                        Toast.makeText(context, "请先配置外部接口地址", Toast.LENGTH_LONG).show()
                        
                        // 记录启用失败日志
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "EXTERNAL_API_TOGGLE",
                            description = "尝试启用外部接口失败：接口地址未配置",
                            oldValue = "禁用",
                            newValue = "启用失败（地址为空）"
                        )
                        return@setOnCheckedChangeListener
                    }
                    
                    // 地址存在，允许启用
                    Toast.makeText(context, "外部接口已启用", Toast.LENGTH_SHORT).show()
                    
                    // 记录启用成功日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "EXTERNAL_API_TOGGLE",
                        description = "启用外部接口",
                        oldValue = "禁用",
                        newValue = "启用 - $currentUrl"
                    )
                } else {
                    // 禁用操作，直接允许
                    Toast.makeText(context, "外部接口已禁用", Toast.LENGTH_SHORT).show()
                    
                    // 记录禁用日志
                    val currentUrl = viewModel.externalApiUrl.value?.trim() ?: ""
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "EXTERNAL_API_TOGGLE",
                        description = "禁用外部接口",
                        oldValue = "启用",
                        newValue = "禁用"
                    )
                }
            }
        }
    }
    
    private fun observeViewModel() {
        // 观察服务器状态
        viewModel.serverStatus.observe(viewLifecycleOwner) { status ->
            serverStatusText.text = status
            updateServerStatusColor(status)
            // 当服务器状态改变时，更新服务器信息显示
            updateServerInfo()
        }
        
        // 观察服务器运行状态
        viewModel.isServerRunning.observe(viewLifecycleOwner) { isRunning ->
            startServerButton.isEnabled = !isRunning
            stopServerButton.isEnabled = isRunning
            // 当服务器运行状态改变时，也更新服务器信息显示
            updateServerInfo()
        }
        
        // 观察网络状态
        viewModel.networkStatus.observe(viewLifecycleOwner) { status ->
            networkStatusText.text = status
        }
        
        // 观察当前端口
        viewModel.currentPort.observe(viewLifecycleOwner) { port ->
            if (portEditText.text.toString() != port.toString()) {
                portEditText.setText(port.toString())
            }
            // 端口改变时更新服务器信息显示
            updateServerInfo()
        }
        
        // 观察当前主机
        viewModel.currentHost.observe(viewLifecycleOwner) { host ->
            if (hostEditText.text.toString() != host) {
                hostEditText.setText(host)
            }
            // 主机改变时更新服务器信息显示
            updateServerInfo()
        }
        // 外部接口地址
        viewModel.externalApiUrl.observe(viewLifecycleOwner) { url ->
            if (externalApiUrlEditText.text.toString() != url) {
                externalApiUrlEditText.setText(url)
            }
        }
        
        // Token
        viewModel.token.observe(viewLifecycleOwner) { token ->
            if (tokenEditText.text.toString() != token) {
                tokenEditText.setText(token)
            }
        }
        
        // 外部接口启用状态
        viewModel.externalApiEnabled.observe(viewLifecycleOwner) { enabled ->
            if (externalApiEnabledSwitch.isChecked != enabled) {
                externalApiEnabledSwitch.isChecked = enabled
                // 初始化完成后，标记为非初始化状态
                isInitializing = false
            }
        }

    }
    
    private fun initializeUI() {
        // 不再设置硬编码的默认值，完全由ViewModel的LiveData驱动
        // ViewModel会在init中从数据库加载配置，如果不存在则使用默认值
        // 通过observeViewModel()中的observe会自动更新UI
        
        // 更新服务器信息
        updateServerInfo()
    }
    
    private fun getPortFromInput(): Int {
        return try {
            portEditText.text.toString().toInt()
        } catch (e: NumberFormatException) {
            KtorServer.DEFAULT_PORT
        }
    }
    
    private fun getHostFromInput(): String {
        return hostEditText.text.toString().ifEmpty { KtorServer.DEFAULT_HOST }
    }
    
    private fun updateServerStatusColor(status: String) {
        val color = if (status.contains("运行中")) {
            android.graphics.Color.GREEN
        } else {
            android.graphics.Color.RED
        }
        serverStatusText.setTextColor(color)
    }
    
    private fun updateServerInfo() {
        serverInfoText.text = viewModel.getServerInfo()
    }
    
    override fun onResume() {
        super.onResume()
        // 页面恢复时更新服务器信息
        updateServerInfo()
    }
} 